package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.service.exception.GuiguException;
import com.atguigu.spzx.common.service.util.AuthContextUtil;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: SysUserServiceImpl
 * @Package: com.atguigu.spzx.manager.service.impl
 * @Description
 * @Author 孤妤
 * @Date: 2023/12/3 16:35
 */
@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper; //mapper
    @Autowired
    private RedisTemplate<String,String> redisTemplate; //redis

    /**
     *
     * @param loginDto
     * @return LoginVo
     */
    @Override
    @Transactional(readOnly = true)
    public LoginVo login(LoginDto loginDto) {
        // 检验验证码
        String code = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();
        // 验空
        if (StrUtil.isEmpty(code)){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        // 从redis中获取验证码校验
        String codeRedis = redisTemplate.opsForValue().get("user:code:" + codeKey);
        if (StrUtil.isEmpty(codeRedis) || !StrUtil.equalsIgnoreCase(codeRedis , code)){
            throw new GuiguException(ResultCodeEnum.CODE_ERROR);
        }
        // 删除验证码
        redisTemplate.delete("user:code:"+codeKey);
        // 获取账户与密码
        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();
        // 验空
        if (StrUtil.isEmpty(userName) || StrUtil.isEmpty(password)){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        // 调用mapper方法获取用户对象,查看是否有该对象
        SysUser sysUser = sysUserMapper.selectByUserName(userName);
        if (sysUser == null){
            throw new GuiguException(ResultCodeEnum.ACCOUNT_NOT_EXSIT);
        }
        // 校验密码,输入的密码加密进行比较
        String md5PassWd = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5PassWd.equals(sysUser.getPassword())){
            throw new GuiguException(ResultCodeEnum.PASSWORD_ERROR);
        }
        // 查看账号是否停用
        if (sysUser.getStatus().intValue() == 0){
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }
        // 生成令牌，保存数据到Redis中
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set("user:login:"+token, JSONObject.toJSONString(sysUser),1, TimeUnit.HOURS);
        // 创建返回给前端token对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        SysUser sysUser = AuthContextUtil.get();
        return sysUser;
    }
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:"+token);
    }
}
